<?php
	include 'config.php';
	
	$username = trim($_POST['username']);
	$password = trim($_POST['password']);
	
	$username = stripslashes($username);
	$password = stripslashes($password);
	$username = mysqli_real_escape_string($con, $username);
	$password = mysqli_real_escape_string($con, $password);
	$password = md5($password);
	
	$stmt = $con->prepare('SELECT User.Login, User.UserRoleID, User.Active, User.CompanyID, Company.Name AS CompanyName FROM User INNER JOIN Company ON User.CompanyID = Company.ID WHERE Login = ? AND Password = ?');
	$stmt->bind_param('ss', $username, $password);
	$stmt->execute();
	$result = $stmt->get_result();

	$count=mysqli_num_rows($result);
	if($count == 1)
	{
		$row = $result->fetch_assoc();
		if($row['Active'] == 1)
		{
			session_start();
			if(isset($_SESSION['message']))
			{
				unset($_SESSION['message']);
			}
			
			$_SESSION['login'] = true;
			$_SESSION['username'] = $username;
			$_SESSION['userroleid'] = $row['UserRoleID'];
			$_SESSION['companyID'] = $row['CompanyID'];
			$_SESSION['companyName'] = $row['CompanyName'];
			switch($row['UserRoleID'])
			{
				case 1:
				case 2:
					header ("Location: listusers.php");
					break;
				default:
					$_SESSION['message'] = "Your employee account is not yet implemented.";
					header ("Location: index.php");
					break;
			}
		}
		else
		{
			session_start();
			$_SESSION['message'] = "Your account is inactive. Contact a manager.";
			header ("Location: index.php");
		}
	}
	else
	{
		session_start();
		$_SESSION['message'] ="Wrong Username or Password";
		header ("Location: index.php");
	}

	mysqli_close($con);
	

?>